package com.dodock.banglapapers.server.helper;

import java.io.IOException;

import org.jsoup.Connection;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Text;
import com.google.gson.JsonArray;
import com.google.gson.JsonObject;

public class DDNNewsDetailSamakal {

	//private String BASE_URL = "http://www.samakal.net/";

	public String Generate(String newsid) throws IOException {
		DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();		
//		Lookup data by known key name
		try {
			Entity detailsEntity = datastore.get(KeyFactory.createKey("NewsDetails", "samakal__"+newsid));
			Text text = (Text)detailsEntity.getProperty("data");
			String data = Settings.replaceExtras(text.getValue());
			return data;
			
		} catch (EntityNotFoundException e) {
			String url = newsid;
			//Document doc = Jsoup.connect(url).get();
			Connection.Response response = Jsoup.connect(url)
		            .userAgent("Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/535.21 (KHTML, like Gecko) Chrome/19.0.1042.0 Safari/535.21")
		            .timeout(10000)
		            .execute();
			
			Document doc = response.parse();
			JsonObject news = new JsonObject();
			news.addProperty("id", newsid);
			news.addProperty("sharelink", url);
			Element newsDetailElement = doc.select("div[id=newsDtl]").first();
			if (newsDetailElement != null) {
				JsonArray imageArray = new JsonArray();
				Elements imageElements = newsDetailElement.select("img");
				String image;
				for (Element imageElement : imageElements) {
					image = imageElement.attr("src").trim();				
					JsonObject obj = new JsonObject();
					obj.addProperty("url", image);
					imageArray.add(obj);
				}

				news.addProperty("details", newsDetailElement.text().replaceAll("\u00a0", "<br/>"));
				news.add("gallery", imageArray);
				
				String data = news.toString();
				data = Settings.replaceExtras(data);
				Text text = new Text(data);
				/* save here */
				Entity detailsEntity = new Entity("NewsDetails", "samakal__"+newsid);
				detailsEntity.setProperty("data", text);
				datastore.put(detailsEntity);
				return data;
			} else{
				return "{}";
			}
		}
	}

}
